package com.gszcn.tools.table.metadata;


import com.gszcn.tools.table.metadata.javadoc.SqlItem;
import com.gszcn.tools.table.metadata.javadoc.SqlJSON;

import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import java.io.*;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 类执行器
 */
class SqlMetar {

    static final String PRIVATE = "private";
    static final String PUBLIC = "public";
    /**
     * 类型工具类
     */
    private TypeUtils typeUtils;



    public SqlMetar(Element element, ProcessingEnvironment environment) {
        typeUtils = new TypeUtils(environment);
        String qualifiedName = typeUtils.getQualifiedName(element);
        Filer filer = environment.getFiler();

        //ClassJavadoc classDoc = parseJavadocResource(qualifiedName);
        System.out.println("filer:" + filer);
        getClassFile(qualifiedName, "java");
    }
    private int num=0;
    private String qualifiedName="";
    private void getClassFile(String qualifiedName, String suff) {
        this.qualifiedName=qualifiedName;
        URL resource = SqlMetadata.class.getResource("/");
        System.out.println(resource);
        File parentFile = new File(resource.getPath()).getParentFile();
        /**
         * 项目位置
         */
        String path = parentFile.getParentFile().getPath();
        String s = path + "/src/main/java/";
        File fileso = new File(s + qualifiedName.replaceAll("\\.", "/") + "." + suff);
        try {
            FileReader fileReader = new FileReader(fileso);
            BufferedReader bReader = new BufferedReader(fileReader);//new一个BufferedReader对象，将文件内容读取到缓存
            StringBuilder sb = new StringBuilder();
            /*读取字符行*/
            String sf = "";
            /*读取注释行*/
            boolean flag=true;
            boolean recomment=false;
            /*注释存储位置*/
            String comment ="";
            /*行号*/

            while ((sf = bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
                /**
                 * 去除空格
                 */
                sf=sf.trim();
                if(!isImport(sf)) {
                    sb.append(sf + "\n");//将读取的字符串添加换行符后累加存放在缓存中
                    flag=isFlag(num,sf);
                    if(!flag|| sf.indexOf("//")!=-1){
                        flag =false;
                        recomment=false;
                        comment=comment+sf+" ";
                    }

                    if (flag&&sqlJSON.getClassname() == null) {
                        sqlJSON=sqlJSONTable(sf);
                    }
                    if (flag){
                        SqlItem sqlItem = sqlItem(sf);
                        if(sqlItem !=null){
                            /**
                             * 添加备注
                             */
                            sqlItem.setComment(comment.replaceAll("\\*|\\/","").trim());
                            recomment=true;
                            sqlJSON=sqlJSON.addSqlItem(sqlItem);
                        }else {
                            recomment=false;
                        }
                    }
                    /**
                     * 表备注
                     */
                    if(sqlJSON.getSqlItems().isEmpty()&& sf.indexOf(" class ")!=-1){
                        sqlJSON.setComment(comment.replaceAll("\\*|\\/","").trim());
                        recomment=true;
                    }
                    if(recomment||sf.indexOf("/**")!=-1){
                        comment="";
                    }
                }
                this.num++;
            }
            if(sqlJSON.getClassname()==null){
                sqlJSON=sqlJSON.name(camel2Underline(qualifiedName.substring(qualifiedName.lastIndexOf(".")+1,qualifiedName.length())));
            }
            bReader.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static SqlItem sqlItem(String sf) {
        if(sf.endsWith(";")&&sf.indexOf("serialVersionUID")==-1&&sf.indexOf(" class ")==-1&&sf.indexOf(")")==-1){
            SqlItem sqlItem = new SqlItem();
            sf=sf.replaceAll(";","");
            String[] split = sf.split("\\s+");

            if(split[0].endsWith(PRIVATE)||split[0].endsWith(PUBLIC)){
                sqlItem.setName(camel2Underline(split[2]));
                sqlItem.setType(split[1]);
            }else{
                sqlItem.setName(camel2Underline(split[1]));
                sqlItem.setType(split[0]);
            }
            return sqlItem;
        }
        return null;
    }

    public TypeUtils getTypeUtils() {
        return typeUtils;
    }

    /**
     * 驼峰法转下划线
     *
     * @param line
     *            源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase()
                .concat(line.substring(1));
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }

    public static void main(String[] args) {

    }

    public SqlJSON sqlJSON = new SqlJSON();

    public SqlJSON getSqlJSON() {
        return sqlJSON;
    }

    private SqlJSON sqlJSONTable(String s) {
        if (s.indexOf("@Table") != -1 && s.indexOf("name") != -1) {
            sqlJSON = sqlJSON.name(s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\"")));
        }
        return sqlJSON;
    }
    /**
     * 判断注释区间
     * 如果不在注释区间返回true
     * 在注释区间返回false
     */
    private static Boolean isFlag(int num,String s){
        /**
         * 多行注释
         */
        if(s.indexOf("/**")!=-1||s.indexOf("*")!=-1){
            /*开启注释行*/
            return false;
        }
        /*关闭注释行*/
        if(s.indexOf("*/")!=-1){
            return true;
        }
        return true;
    }

    private static Boolean isImport(String s){
        if(s.indexOf("import ")!=-1||s.indexOf("package ")!=-1){
            return true;
        }
        return false;
    }
}
